package com.huawei.common.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class DirClassPathLoader {
	private static Method addMethod;
	private static URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
	static {
		initMethod();
	}

	public static void initMethod() {
		try {
			addMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
			addMethod.setAccessible(true);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}
	}

	public static void addDirClassPath(String path)
			throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, MalformedURLException {
		File file = new File(path);
		if (file.exists()) {
			deleteFolder(file);
		}
		file.mkdir();
		addMethod.invoke(classLoader, file.toURI().toURL());
	}

	public static void deleteFolder(File file) {
		File[] files = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {
					deleteFolder(file);
				} else {
					f.delete();
				}
			}
		}
	}
}
